package fourfaith.com.ff_sl21_app.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import fourfaith.com.ff_sl21_app.AlarmActivity;
import fourfaith.com.ff_sl21_app.DeviceActivity;
import fourfaith.com.ff_sl21_app.HistoryActivity;
import fourfaith.com.ff_sl21_app.MonitorActivity;
import fourfaith.com.ff_sl21_app.PictureActivity;
import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.RemoteConfigActivity;
import fourfaith.com.ff_sl21_app.VideoActivity;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;
import fourfaith.com.ff_sl21_app.weather.CalendarTime;
import fourfaith.com.ff_sl21_app.weather.Result;
import fourfaith.com.ff_sl21_app.weather.Weather_data;
import fourfaith.com.ff_sl21_app.weather.httpUtils;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment{

    private TextView todayWeather;
    private ImageView weatherPic;
    private TextView todayAlarmCount,noReadNoticeCount,onlineDeviceCount, allDeviceCount;
    private LinearLayout deviceManage,alarmManage,monitorManage,historyDataManage,pictureManage,videoManage;
    private Context ctx ;

    private JsonRequest jsonRequest;

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home,container,false);
        //mTextView = (TextView)getActivity().findViewById(R.id.txt_content);
        ctx = getActivity();
        initView(view);
        return view;
    }

    public void initView(View view){

        deviceManage = (LinearLayout) view.findViewById(R.id.deviceManage);
        alarmManage = (LinearLayout) view.findViewById(R.id.alarmManage);
        monitorManage = (LinearLayout) view.findViewById(R.id.monitorManage);
        historyDataManage = (LinearLayout) view.findViewById(R.id.historyDataManage);
        pictureManage = (LinearLayout) view.findViewById(R.id.pictureManage);
        videoManage = (LinearLayout) view.findViewById(R.id.videoManage);

        deviceManage.setOnClickListener(listener);
        alarmManage.setOnClickListener(listener);
        monitorManage.setOnClickListener(listener);
        historyDataManage.setOnClickListener(listener);
        pictureManage.setOnClickListener(listener);
        videoManage.setOnClickListener(listener);

        allDeviceCount = (TextView)view.findViewById(R.id.allDeviceCount);
        todayAlarmCount = (TextView)view.findViewById(R.id.todayAlarmCount);
        noReadNoticeCount = (TextView)view.findViewById(R.id.noReadNoticeCount);
        onlineDeviceCount = (TextView)view.findViewById(R.id.onlineDeviceCount);

        todayWeather = (TextView)view.findViewById(R.id.todayWeather);
        weatherPic = (ImageView)view.findViewById(R.id.weatherPic);
        SharedPreferences weatherInfo = getActivity().getSharedPreferences("today_weather", 0);
        if(weatherInfo!=null){
            todayWeather.setText(weatherInfo.getString("temperature", ""));
            weatherPic.setImageResource(weatherInfo.getInt("picId",0));
        }
        WeatherAsyncTask weatherAsyncTask =  new WeatherAsyncTask();

        String url = "http://api.map.baidu.com/telematics/v3/weather?location=%E5%8E%A6%E9%97%A8&output=json&ak=VvaQaeGRqy3pmey61T3qQMWz&mcode=34:13:19:F5:0F:C2:1B:E1:AA:B1:D9:5B:B3:B1:F6:E9:FC:9D:BE:6E;com.fourfaith";
//            String jsonStr = httpUtils.get(url);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        String jsonStr =response;
                        List<Result> result = weatherAsyncTask.fromJson(jsonStr);

                        if(result!=null){
                            Result res = result.get(0);
                            Weather_data wa = res.getWeather_data().get(0);

                            //获取当前日期
                            java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
                            java.util.Calendar calendar = java.util.Calendar.getInstance();
                            CalendarTime chinaTime = new CalendarTime(calendar);

                            int picId;

                            //今天
                            picId = weatherAsyncTask.getPicId(wa.getDayPictureUrl());

                            todayWeather.setText(wa.getTemperature());
                            weatherPic.setImageResource(picId);

                            SharedPreferences sp = getActivity().getSharedPreferences("today_weather", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("temperature", wa.getTemperature());
                            editor.putInt("picId", picId);
                            editor.commit();


                        }else{
				/*	//现在只考虑配额超出的问题
    			  new AlertDialog.Builder(this);
			     .setTitle("超出配额提示")
			     .setMessage("百度天气API每天只提供小于5000次的天气服务")
			     .show(); */
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        Volley.newRequestQueue(getContext()).add(stringRequest);
        requestHomeData();
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.deviceManage:
                    startActivity(new Intent(ctx, DeviceActivity.class));
                    break;
                case R.id.alarmManage:
                    startActivity(new Intent(ctx, RemoteConfigActivity.class));
                    break;
                case R.id.monitorManage:
                    startActivity(new Intent(ctx, MonitorActivity.class));
                    break;
                case R.id.historyDataManage:
                    startActivity(new Intent(ctx, HistoryActivity.class));
                    break;
                case R.id.pictureManage:
                    Intent picIntent = new Intent();
                    picIntent.setClass(getActivity(),PictureActivity.class);
                    startActivity(picIntent);
                    break;
                case R.id.videoManage:
                    Intent videoIntent = new Intent();
                    videoIntent.setClass(getActivity(), VideoActivity.class);
                    startActivity(videoIntent);
                    break;
            }
        }
    };

    /**
     * 请求主页数据
     */
    private void requestHomeData() {

        String loginUrl = Constants.homeData + "?userId=" + Constants.getUserId() ;

        RequestQueue mQueue = RequestQueueSingleton.getInstance(getActivity()).getRequestQueue();

        jsonRequest = new JsonRequest<>(Request.Method.GET, loginUrl, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult obj) {
                        if (obj.getCode().equals("200")) {
                            Object objData = obj.getData();//获取用户的数据
                            try {
                                com.alibaba.fastjson.JSONObject result = (com.alibaba.fastjson.JSONObject) JSON.toJSON(objData);

                                todayAlarmCount.setText(String.valueOf(result.get("todayAlarmCount")));
                                noReadNoticeCount.setText(String.valueOf(result.get("noReadNoticeCount")));
                                onlineDeviceCount.setText(String.valueOf(result.get("onlineDeviceCount")));
                                allDeviceCount.setText(String.valueOf(result.get("allDeviceCount")));

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(getActivity(), obj.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

        });
        mQueue.add(jsonRequest);
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    class WeatherAsyncTask extends AsyncTask<String, Void, List<Result>> {

        @Override
        protected List<Result> doInBackground(String... params) {
            String url = "http://api.map.baidu.com/telematics/v3/weather?location=%E5%8E%A6%E9%97%A8&output=json&ak=VvaQaeGRqy3pmey61T3qQMWz&mcode=34:13:19:F5:0F:C2:1B:E1:AA:B1:D9:5B:B3:B1:F6:E9:FC:9D:BE:6E;com.fourfaith";
            String jsonStr = httpUtils.get(url);
            List<Result> weather = fromJson(jsonStr);
            return weather;
        }

        protected void onPostExecute(List<Result> result) {
            if(result!=null){
                Result res = result.get(0);
                Weather_data wa = res.getWeather_data().get(0);

                //获取当前日期
                java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Calendar calendar = java.util.Calendar.getInstance();
                CalendarTime chinaTime = new CalendarTime(calendar);

                int picId;

                //今天
                picId = getPicId(wa.getDayPictureUrl());

                todayWeather.setText(wa.getTemperature());
                weatherPic.setImageResource(picId);

                SharedPreferences sp = getActivity().getSharedPreferences("today_weather", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("temperature", wa.getTemperature());
                editor.putInt("picId", picId);
                editor.commit();


            }else{
				/*	//现在只考虑配额超出的问题
    			  new AlertDialog.Builder(this);
			     .setTitle("超出配额提示")
			     .setMessage("百度天气API每天只提供小于5000次的天气服务")
			     .show(); */
            }
        }

        private List<Result> fromJson(String jsonStr) {
            try{
                JSONObject obj = new JSONObject(jsonStr);
                String status = obj.getString("status");
                if(status.equals("success")){
                    String error = obj.getString("error");
                    // 根据具体的error值返回不同的信息，这儿做了统一处理，返回null;
                    if (Integer.parseInt(error) != 0) {
                        return null;
                    } else {
                        // results信息
                        List<Result> results = new ArrayList<Result>();
                        JSONArray rArr = obj.getJSONArray("results");
                        for (int i = 0; i < rArr.length(); i++){
                            JSONObject rObj = rArr.getJSONObject(i);
                            Result res = new Result();
                            res.setCurrentCity(rObj.getString("currentCity"));//当前城市
                            res.setPm25(rObj.getString("pm25"));

                            // weather_data信息
                            List<Weather_data> weather_data = new ArrayList<Weather_data>();
                            JSONArray wArr = rObj.getJSONArray("weather_data");
                            for (int j = 0; j < wArr.length(); j++) {
                                JSONObject wObj = wArr.getJSONObject(j);
                                Weather_data wd = new Weather_data();
                                wd.setDate(wObj.getString("date"));//周四 08月27日 (实时：34℃)
                                wd.setDayPictureUrl(wObj.getString("dayPictureUrl"));//http://api.map.baidu.com/images/weather/day/leizhenyu.png
                                wd.setNightPictureUrl(wObj.getString("nightPictureUrl"));//http://api.map.baidu.com/images/weather/night/leizhenyu.png
                                wd.setWeather(wObj.getString("weather"));//雷阵雨
                                wd.setWind(wObj.getString("wind"));//微风
                                wd.setTemperature(wObj.getString("temperature"));//34 ~ 26℃
                                weather_data.add(wd);
                            }
                            res.setWeather_data(weather_data);
                            results.add(res);
                        }
                        return results;
                    }
                }else{
                    return null;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        private int getPicId(String picUrl){
            int weather  = R.mipmap.sunny;
            picUrl = picUrl.substring(picUrl.lastIndexOf('/') + 1, picUrl.lastIndexOf('.'));
            List<String> list = Arrays.asList("qing", "yin", "wu", "duoyun", "shachenbao", "fuchen", "yangsha", "qiangshachenbao", "mai"
                    , "xiaoyu", "zhongyu", "dayu", "baoyu", "dabaoyu", "tedabaoyu"
                    , "xiaoyuzhuanzhongyu", "zhongyuzhuandayu", "dayuzhuanbaoyu", "baoyuzhuandabaoyu", "dabaoyuzhuantedabaoyu"
                    , "dongyu", "zhenyu", "leizhenyu", "leizhenyubanyoubingbao"
                    , "zhenxue", "xiaoxue", "zhongxue", "daxue", "baoxue", "xiaoxuezhuanzhongxue", "zhongxuezhuandaxue", "daxuezhuanbaoxue"
                    , "yujiaxue");
            switch(list.indexOf(picUrl)){
                case 0:
                    weather = R.mipmap.sunny;
                    break;
                case 1:
                    weather = R.mipmap.shady;
                    break;
                case 2:
                    weather = R.mipmap.fog;
                    break;
                case 3:
                    weather = R.mipmap.cloudy;
                    break;
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                    weather = R.mipmap.haze;
                    break;
                case 9:
                case 10:
                case 11:
                case 12:
                case 13:
                case 14:
                case 15:
                case 16:
                case 17:
                case 18:
                case 19:
                    weather = R.mipmap.rainy;
                    break;
                case 20:
                case 21:
                case 22:
                case 23:
                    weather = R.mipmap.thunder;
                    break;
                case 24:
                case 25:
                case 26:
                case 27:
                case 28:
                case 29:
                case 30:
                case 31:
                    weather = R.mipmap.snow;
                    break;
                case 32:
                    weather = R.mipmap.rainsnow;
                    break;
            }
            return weather;
        }
    }

}
